package com.t4.process.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.t4.common.exception.T4Exception;
import com.t4.common.result.ResultCodeEnum;
import com.t4.model.process.ProcessTemplate;
import com.t4.model.process.ProcessType;
import com.t4.process.mapper.ProcessTemplateMapper;
import com.t4.process.mapper.ProcessTypeMapper;
import com.t4.process.service.ProcessService;
import com.t4.process.service.ProcessTemplateService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.List;

@Service
public class ProcessTemplateServiceImpl extends ServiceImpl<ProcessTemplateMapper, ProcessTemplate> implements ProcessTemplateService {

    @Resource
    private ProcessTypeMapper processTypeMapper;

    @Resource
    private ProcessService processService;

    @Override
    public IPage<ProcessTemplate> pageWithProcessType(Page<ProcessTemplate> pageParam) {
        // 1. 调用原本的分页查询
        IPage<ProcessTemplate> processTemplatePage = baseMapper.selectPage(pageParam, null);
        // 2. 获取分页结果中的数据列表，遍历，根据typeId找到typeName
        List<ProcessTemplate> records = processTemplatePage.getRecords();
        for(ProcessTemplate processTemplate: records){
            ProcessType processType = processTypeMapper.selectById(processTemplate.getProcessTypeId());
            if(processType == null){
                continue;
            }
            processTemplate.setProcessTypeName(processType.getName());
        }
        return processTemplatePage;
    }

    @Transactional
    @Override
    public void publish(Long id) {
        // 1. 修改模板发布状态（1已经发布）
        // 1.1 根据id查询模板
        ProcessTemplate processTemplate = baseMapper.selectById(id);
        if(processTemplate == null){
            throw new T4Exception(ResultCodeEnum.DATA_ERROR);
        }
        // 1.2 如果模板状态不为1，进行修改
        if(processTemplate.getStatus().intValue() != 1){
            processTemplate.setStatus(1);
            baseMapper.updateById(processTemplate);
        }
        // 2. 进行流程定义部署
        if(!StringUtils.isEmpty(processTemplate.getProcessDefinitionPath())){
            processService.deployByZip(processTemplate.getProcessDefinitionPath());
        }
    }
}
